<?php
/**
 * OA文章管理
 *
 * PHP version 5
 *
 * @package   YuDian
 * @author    lw
 * @copyright 2016 Shangyuanruige Inc.
 */
namespace app\controllers;

use app\models\Archives;
use app\models\user\Users;
use common\models\User;
use Yii;
use yii\helpers\ArrayHelper;
use yii\data\Pagination;
use app\components\NoCsrfBehavior;
use yii\web\UploadedFile;

class ArchivesController extends CommonController
{
    public $navTabId;

    public function __construct($id, $module, $config = [])
    {
        $this->id = $id;
        $this->module = $module;

        parent::__construct($config);

        $this->navTabId = "archivesindex";

    }

    /**
     * behaviors
     *
     * @author Fee
     */
    public function behaviors()
    {
        return [
            'csrf' => [
                'class' => NoCsrfBehavior::className(),
                'controller' => $this,
                'actions' => [
                    'index','delete','delall','list'
                ]
            ]
        ];
    }

    /**
     * 显示列表页面
     *
     * @return html
     * @author Fee
     */
    public function actionIndex() {
    	$this->checkAuth($this->id, $this->action->id);
        $school_id = $_SESSION['school_id'];
        $order_arr['add_time'] = SORT_DESC;
        $where['school_id'] = $school_id;
        if (isset($_POST['status']) and $_POST['status']!="") {
            $search['status'] = $_POST['status'];
            $where['status'] = $_POST['status'];
        }
        if (!empty($_POST['orderField'])) {
            $orderField = $_POST['orderField'];

            if (isset ( $_POST['orderDirection'] )) {
                $orderDirection = $_POST['orderDirection'] == 'asc' ? SORT_ASC : SORT_DESC;
            } else {
                $orderDirection = SORT_DESC;
            }

            $order_arr[$orderField] = $orderDirection;
        } else {
            $orderField = "";
            $orderDirection = "";
        }

        if (!empty($_POST['numPerPage'])){
            $numPerPage = $_POST['numPerPage'];
        } else {
            $numPerPage = Yii::$app->params['oa_page_num'];
        }


        $query = Archives::find()->where($where);
        $count = $query->count();

        $pages = new Pagination(['totalCount' => $count, 'pageSize' => $numPerPage]);
        $list = $query->orderBy($order_arr)
                        ->offset($pages->offset)
                        ->limit($pages->limit)
                        ->asArray()
                        ->all();
                        
        return $this->render('index',[
            'list' => $list,
            'orderDirection' => $orderDirection,
            'orderField'     => $orderField,
            'totalCount'     => $count,
            'filters'        => $_POST,
            'numPerPage'     => $pages->limit,
            'currentPage'    => !empty($_POST['p'])?$_POST['p']:1,
        ]);
    }

    /**
     * 新增
     */
    public function actionInserts()
    {
        $model = new Archives();
        $form = Yii::$app->request->post();
        $data['title'] = $form['title'];
        $model->image = UploadedFile::getInstanceByName('image');
        $data['image'] = $model->uploadImg();
        $model->cover_image = UploadedFile::getInstanceByName('cover_image');
        $data['cover_image'] = $model->uploadImage();
        $data['school_id'] = Yii::$app->session['school_id'];
        $data['content'] = empty($form['content']) ? '' : htmlspecialchars_decode($form['content']);
        $data['content'] = empty($form['content']) ? '' : stripslashes($form['content']);
        $data['writer'] = $form['writer'];
        $data['source'] = $form['source'];
        $data['redirecturl'] = $form['redirectUrl'];
        $data['add_time'] = time();
        $result = $model->insertInfo($data);
        if ($result) {
            $this->ajaxReturn(200, Yii::t('app', 'Add success'), $this->navTabId, 1);
        } else {
            $this->ajaxReturn(300, Yii::t('app', 'Add failed, please try again'));
        }
    }

    /**
     * 编辑
     */
    public function actionUpdates()
    {
        $model = new Archives();
        $form = Yii::$app->request->post();
        $data['title'] = $form['title'];
        
        
        $data_model = $this->getModel(intval($form["id"]));

        if (UploadedFile::getInstanceByName('image')) {
            $model->image = UploadedFile::getInstanceByName('image');
            if(!empty($data_model->image)) {
                $old_img_path = Yii::$app->params['upload_ar_path'] . $data_model->image;
                if (is_file($old_img_path)) {
                    @unlink($old_img_path);
                }
            }
            $data['image'] = $model->uploadImg();
        }

        if (UploadedFile::getInstanceByName('cover_image')) {
            $model->cover_image = UploadedFile::getInstanceByName('cover_image');
            if(!empty($data_model->cover_image)) {
                $old_img_path = Yii::$app->params['upload_ar_path'] . $data_model->cover_image;
                if (is_file($old_img_path)) {
                    @unlink($old_img_path);
                }
            }
            $data['cover_image'] = $model->uploadImage();
        }
        $data['content'] = empty($form['content']) ? '' : htmlspecialchars_decode($form['content']);
        $data['content'] = empty($form['content']) ? '' : stripslashes($form['content']);
        $data['writer'] = $form['writer'];
        $data['source'] = $form['source'];
        $data['redirecturl'] = $form['redirectUrl'];
        $result = $model->updateInfo($data, ['id'=>$form['id']]);
        if ($result) {
            $this->ajaxReturn(200, Yii::t('app', 'Editor success'), $this->navTabId, 1);
        } else {
            $this->ajaxReturn(300, Yii::t('app', 'Editor failed, please try again'));
        }
    }

    /**
     * 详情
     * @return string
     */
    public function actionView()
    {
        $id = intval($_GET['id']);
        $item = Archives::find()->where(['id'=>$id])->asArray()->one();
        return $this->render('view', ['item'=>$item,'model' => $this->getModel($id)
            ]);
    }

    /**
     * 单独删除
     *
     * @return json
     * @author Fee
     */
    public function actionDelete($id)
    {   
        $this->checkAuth($this->id, $this->action->id);

        $model = $this->getModel($id);
        
        $school_id = Yii::$app->session["school_id"];

        if($model->school_id != $school_id) {
            $this->ajaxReturn(300, Yii::t('app', 'The record does not exist. Please try again'), $this->navTabId);
        }

        if(!empty($model->image)) {
            $old_img_path = Yii::$app->params['upload_ar_path'] . $model->image;
            if (is_file($old_img_path)) {
                @unlink($old_img_path);
            }
        }

        if(!empty($model->cover_image)) {
            $old_img_path = Yii::$app->params['upload_ar_path'] . $model->cover_image;
            if (is_file($old_img_path)) {
                @unlink($old_img_path);
            }
        }

        $rs = $model->delete();

        if (false !== $rs) {
            $this->ajaxReturn(200, Yii::t('app', 'Delete success'), $this->navTabId);
        } else {
            $this->ajaxReturn(300, Yii::t('app', 'Delete failed, please try again'), $this->navTabId);
        }
    }

    /**
     * 批量删除
     *
     * @return json
     * @author Fee
     */
    public function actionDelall()
    {
        $this->checkAuth($this->id, 'delete');

        if(empty($_POST["ids"])) {
            $this->ajaxReturn(300, Yii::t('app', 'Please select a record'));
        }

        $model = $this->getModel();


        $list = $model::find()->where(['in', 'id', explode(',', $_POST["ids"])])
                            ->select(['school_id', 'image','cover_image'])
                            ->all();
        
        $school_id = Yii::$app->session["school_id"];

        foreach ($list as $l) {
            if($l->school_id != $school_id) {
                $this->ajaxReturn(300, Yii::t('app', 'The record does not exist. Please try again'), $this->navTabId);
            }
        }

        foreach ($list as $l) {
            if(!empty($l->image)) {
                $old_img_path = Yii::$app->params['upload_ar_path'] . $l->image;
                if (is_file($old_img_path)) {
                    @unlink($old_img_path);
                }
            }

            if(!empty($l->cover_image)) {
                $old_img_path = Yii::$app->params['upload_ar_path'] . $l->cover_image;
                if (is_file($old_img_path)) {
                    @unlink($old_img_path);
                }
            }
        }

        $rs = $model::deleteAll(['in', 'id', explode(',', $_POST["ids"])]);

        if (false !== $rs) {
            $this->ajaxReturn(200, Yii::t('app', 'Delete success'),$this->navTabId, 0);
        } else {
            $this->ajaxReturn(300, Yii::t('app', 'Delete failed, please try again'), $this->navTabId);
        }
    }

    /**
     * 获取需要传递到界面的额外数据
     *
     * @return html
     * @author Fee
     */
    public function getPageData($id=0)
    {
        return [
            'model' => $this->getModel($id)
            ];
    }

    /**
     * 获取数据
     *
     * @return obj
     * @author Fee
     */
    public function getModel($id=0)
    {
        if($id == 0) {
            return new Archives();
        }

        if (($model = Archives::findOne($id)) !== null) {
            return $model;
        }

        return $this->ajaxReturn(300,Yii::t('app', 'The record does not exist. Please try again'),$this->navTabId, 1);
    }
}